# coding=utf-8
# 全世界最帅的帅哥
from flask import current_app
from ysgg1_club_comment.modules.auth_role import AuthRole
from ysgg1_club_auth.auth_serializers.role_serializer import RoleSerializer
from flask_restful import reqparse
from ysgg1_club_comment.modules import db
from sqlalchemy.exc import OperationalError, SQLAlchemyError
from ysgg1_club_comment.utils.fbmsg import FBMsg


def query_role_by_id(role_id):
    role = AuthRole.query.filter_by(id=role_id, is_delete=0).first()
    if not role:
        return FBMsg.error_param()
    data = RoleSerializer(role).to_dict()
    return data


def create_role():
    try:
        parser = reqparse.RequestParser()
        parser.add_argument('roleName', required=True, help="角色名称不能为空")
        parser.add_argument('roleKey', required=True, help="角色唯一标识不能为空")

        args = parser.parse_args()
        role_name = args.roleName
        role_key = args.roleKey

        role = AuthRole(role_name=role_name, role_key=role_key)
        db.session.add(role)
        db.session.commit()
        current_app.logger.info("新增role成功")
        return {"code": 200, "success": True, "message": "新增role成功"}

    except (Exception, OperationalError, SQLAlchemyError) as e:
        current_app.logger.error(e.__str__())
        db.session.rollback()
        return FBMsg.create_role_error_message()


def update_role(role_id):
    role = AuthRole.query.filter_by(id=role_id, is_delete=0).first()
    if not role:
        return FBMsg.error_param()

    parser = reqparse.RequestParser()
    parser.add_argument('roleName')
    parser.add_argument('roleKey')

    args = parser.parse_args()
    role_name = args.roleName
    role_key = args.roleKey

    role.role_name = role_name if role_name else role.role_name
    role.role_key = role_key if role_key else role.role_key

    db.session.add(role)
    db.session.commit()
    current_app.logger.info(f"修改role_id为{role_id}成功")
    return {"code": 200, "success": True, "message": "修改role成功"}


def delete_role(role_id):
    role = AuthRole.query.filter_by(id=role_id, is_delete=0).first()
    if not role:
        return FBMsg.error_param()
    role.is_delete = 1

    db.session.add(role)
    db.session.commit()
    current_app.logger.info(f"删除role_id为{role_id}成功")
    return {"code": 200, "success": True, "message": "删除role成功"}